package com.briup.common.config;

import com.briup.common.properties.DateConverterConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 全局接收日期参数的格式转换配置类
 */
@ConditionalOnProperty("briup.config.date-converter.format")
@Configuration
public class WebDateConverterAutoConfig implements WebMvcConfigurer {

	@Autowired
	private DateConverterConfigProperties dateConverterConfigProperties;

	// 添加全局接收日期参数时候的转换器
	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverter(new StringToDateConverter());
	}

	// 配置全局转换器
	// 例如，yyyy-MM-dd HH:mm:ss
	class StringToDateConverter implements Converter<String, Date> {

		@Override
		public Date convert(String source) {
			Date target = null;
			if(StringUtils.hasLength(source)) {
				// 保存一下当前参数，如果添加时分秒报错，那么可以不添加时分秒再试试
				String sourceBak = source;

				// 如果是传的时候 1999-11-11 则自动添加为 1999-11-11 00:00:00
				if(!source.contains(":")){
					source = source.trim()+" 00:00:00";
				}
				SimpleDateFormat format = new SimpleDateFormat(dateConverterConfigProperties.getFormat());
				try {
					target = format.parse(source);
				} catch (Exception e1) {
					try {
						target = format.parse(sourceBak);
					} catch (Exception e2) {
						throw new RuntimeException(String.format("parser %s to Date fail", sourceBak));
					}
				}
			}
			return target;
		}
	}

}
